package com.kitty.game.shop;

import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.config.Grocery;
import com.kitty.game.config.NPC;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespNotifyMisc;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.item.ItemDataPool;
import com.kitty.game.item.service.PetStoneService;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.NotifyModules;
import com.kitty.mina.message.MessagePusher;
import com.kitty.game.base.service.BagService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShopService {
    @Resource
    private Dao dao;
    @Resource
    private MallService mallService;
    @Resource
    private EquipService equipService;

    private static final String SUCCESS_MESSAGE = "你购买了#R{0}#n{1}#R{2}#n，花费{3}文{4}#n。";


    public void init() {
        List<Grocery> groceries = dao.query(Grocery.class, Cnd.NEW());
        Map<Short, Grocery> pos2Grocery = new HashMap<>(groceries.size());
        groceries.forEach(grocery -> pos2Grocery.put(grocery.getGoods_no(), grocery));
        ItemDataPool.pos2Grocery = pos2Grocery;
    }

    /**
     * 发送杂货店
     */
    public void sendGroceryShop(Role role, NPC npc) {
        List<ItemInfo> itemInfos = new ArrayList<>();
        ItemDataPool.pos2Grocery.values().forEach(grocery -> itemInfos.add(getItemInfo(grocery)));
        RespGoodsList respGoodsList = new RespGoodsList();
        respGoodsList.setNpcId(npc.getId());
        respGoodsList.setList(itemInfos);
        respGoodsList.setType((short) 1);
        MessagePusher.pushMessage(role, respGoodsList);
    }

    private ItemInfo getItemInfo(Grocery grocery) {
        ItemInfo itemInfo = new ItemInfo();
        itemInfo.setName(grocery.getName());
        itemInfo.setPos(grocery.getGoods_no());
        itemInfo.setPrice(grocery.getPrice());
        itemInfo.setLevel(grocery.getLevel());
        itemInfo.setPay_type(grocery.getPay_type());
        itemInfo.setType(grocery.getType());
        return itemInfo;
    }

    /**
     * 购买杂货
     */
    public void buyGrocery(Role role, short pos, short num) {
        Grocery grocery = ItemDataPool.pos2Grocery.get(pos);
        if (grocery == null) {
            return;
        }
        short newPos = SpringUtils.getBean(BagService.class).getPos(role, false);
        if (newPos <= 0) {
            MessagePusher.pushMessage(role, new RespMsg("你的包裹已满。"));
            return;
        }
        if (!grocery.isSale()) {
            MessagePusher.pushMessage(role, new RespMsg("该物品未开放购买。"));
            return;
        }

        boolean useVoucher = role.isUseVoucher();//真 使用代金券 假 使用金钱
        int needMoney = grocery.getPrice() * num;
        if (useVoucher) {
            if (role.getVoucher() < needMoney) {
                RespMsg respMsg = new RespMsg();
                respMsg.setMsg("你的代金券不足。");
                MessagePusher.pushMessage(role, respMsg);
                return;
            } else {
                role.setVoucher(role.getVoucher() - needMoney);
            }
        } else {
            if (role.getMoney() < needMoney) {
                RespMsg respMsg = new RespMsg();
                respMsg.setMsg("你的金钱不足！请到积分商城购买");
                MessagePusher.pushMessage(role, respMsg);
                return;
            } else {
                RoleService roleService = SpringUtils.getBean(RoleService.class);
                roleService.subtractMoney(role,  needMoney);
            }
        }

        /**TODO 物品类型都不同 属性不同 用什么方式处理呢*/
        if (grocery.getType() == 2) {//妖石
            SpringUtils.getBean(PetStoneService.class).getPetStone(role, grocery.getName(), newPos, useVoucher, grocery.getLevel(), num);
        } else if (grocery.getName().equals("九曲玲珑笔")) {
            getSharpPen(role, newPos, useVoucher);
        }else if(grocery.getName().equals("驯兽诀") || grocery.getName().equals("如意刷道令")){
            equipService.addMall(grocery.getName(),useVoucher,role);
        }else if (grocery.getName().contains("烟花筒")) {//烟花筒
            RoleEquip roleEquip = new RoleEquip();
            roleEquip.setType("道具");
            int id = mallService.getRoleEquipId();
            roleEquip.setId(id);
            roleEquip.setName(grocery.getName());
            roleEquip.setRoleId(role.getRoleId());
            roleEquip.setPosition(pos);
            equipService.add(role, roleEquip);
            equipService.refreshRoleEquip(role, roleEquip);

            RespIconCartoon respIconCartoon = new RespIconCartoon();
            respIconCartoon.setType((short) 2);
            respIconCartoon.setName(roleEquip.getName());
            respIconCartoon.setParam(roleEquip.getId() + "");
            MessagePusher.pushMessage(role, respIconCartoon);

            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你获得了#R" + num + "#n块#R" + roleEquip.getName() + "#n。"));
        }
        SpringUtils.getRoleService().updateRoleMoney(role);
        role.save();
        MessagePusher.pushMessage(role, new RespNotifyMisc(MessageFormat.format(SUCCESS_MESSAGE, num, getItemUnit(grocery.getName()), grocery.getName(), AsktaoUtil.getMoneyFormat(needMoney), (useVoucher ? "代金券" : "金钱"))));
        //发送购买完成的协议 才可以再次购买
        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setValue("goods");
        respGeneralNotify.setNotify((short)NotifyModules.NOTIFY_BUY_FINISHED);//够买成功
        MessagePusher.pushMessage(role, respGeneralNotify);
    }


    private String getItemUnit(String name) {
        return SpringUtils.getBean(MallService.class).getSpecialItem(name).getUnit();
    }

    private void getSharpPen(Role role, short pos, boolean isLimit) {
        RoleEquip roleEquip = new RoleEquip();
        roleEquip.setType("其他道具");
        int id = mallService.getRoleEquipId();
        roleEquip.setId(id);
        roleEquip.setName("九曲玲珑笔");
        roleEquip.setRoleId(role.getRoleId());
        roleEquip.setPosition(pos);
        setBasicAttr(roleEquip, isLimit);
        equipService.add(role, roleEquip);
        equipService.refreshRoleEquip(role, roleEquip);

        RespIconCartoon respIconCartoon = new RespIconCartoon();
        respIconCartoon.setName(roleEquip.getName());
        respIconCartoon.setParam(roleEquip.getId() + "");
        MessagePusher.pushMessage(role, respIconCartoon);

    }

    private void setBasicAttr(RoleEquip roleEquip, boolean isLimit) {
        LinkedHashMap<Short, FiedValue> basic = new LinkedHashMap<>();
        List<FiedValue> values = new ArrayList<>();
        values.add(new FiedValue(205, 0));
        values.add(new FiedValue(206, 260));
        values.add(new FiedValue(74, 5));
        values.add(new FiedValue(43, 10));
        values.add(new FiedValue(42, 10));
        values.add(new FiedValue(40, 9704));
        values.add(new FiedValue(207, 500));
        values.add(new FiedValue(1, "九曲玲珑笔"));
        values.add(new FiedValue(306, String.valueOf(roleEquip.getId())));
        values.add(new FiedValue(209, ""));
        values.add(new FiedValue(84, roleEquip.getId()));
        values.add(new FiedValue(270, isLimit ? 2 : 0));
        values.add(new FiedValue(203, 1));
        values.add(new FiedValue(282, Const.ITEM_COMBINED_NO));
        values.forEach(fieldValue -> basic.put(fieldValue.getType(), fieldValue));
        RoleEquipField roleEquipField = new RoleEquipField();
        roleEquipField.setType((short) 1);
        roleEquipField.setField(basic);
        roleEquip.getFields().put(roleEquipField.getType(), roleEquipField);
    }
}
